package com.kun.dynamic.config;

import com.kun.dynamic.core.DynamicDataSource;
import com.kun.dynamic.event.DynamicUpdateDsEvent;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.util.Assert;

import java.util.Map;

/**
 * 动态改变数据源配置类
 * @author kun.li
 */
@Configuration(proxyBeanMethods = false)
public class ChangeDataSourceConfig {

    @Resource
    private DynamicDataSource dynamicDataSource;

    @EventListener(DynamicUpdateDsEvent.class)
    public void updateDs(DynamicUpdateDsEvent dynamicUpdateDsEvent) {
        Map<Object, Object> targetDsMap = (Map<Object, Object>) dynamicUpdateDsEvent.getSource();
        Object master = targetDsMap.get("master");
        Assert.notNull(master,"必须有一个 key 为 master的数据源");
        dynamicDataSource.setTargetDataSources(targetDsMap);
        dynamicDataSource.setDefaultTargetDataSource(master);
        dynamicDataSource.afterPropertiesSet();
    }
}
